﻿using System;
using System.Data;
using System.Linq;
using System.Windows.Forms;
using Telerik.WinControls.UI;
using Zvezda.FSO2.DB;
using Zvezda.FSO2.DB.DataSetFSOTableAdapters;


namespace FSO
{
    public partial class FormGuildBill : Form, InterfaceObjDeleteableForm
    {
        DataSetFSO.GUILD_BILLRow _guildBillRow;
		public bool AllowSave;

        public FormGuildBill(int? pid)
        {
            InitializeComponent();
            if (pid == null)
            {

            }
            else
            {
                CONTRACTTableAdapter taContract = new CONTRACTTableAdapter();


                _guildBillRow = dataSetFSO1.GUILD_BILL.NewGUILD_BILLRow();

                _guildBillRow.PID = pid.Value;
                //Полю "Дата" по умолчанию присваиваем сегодняшнее число
                _guildBillRow.DATE = DateTime.Now.Date;

                dataSetFSO1.GUILD_BILL.AddGUILD_BILLRow(_guildBillRow);
            }
        }

        public FormGuildBill(DataSetFSO.GUILD_BILLRow row)
        {
            InitializeComponent();

            guilD_BILLTableAdapter1.FillByID(dataSetFSO1.GUILD_BILL, row.ID);
            _guildBillRow = dataSetFSO1.GUILD_BILL.FindByID(row.ID);

            this.Text = "Цехова накладная № " + _guildBillRow.NUMBER;
        }

        public int Delete()
        {
            int returnValue = -1;

            foreach (DataSetFSO.VIEW_GUILD_BILL_ITEMRow row in dataSetFSO1.VIEW_GUILD_BILL_ITEM.Rows)
            {
                if (row.RowState != DataRowState.Deleted && row.RowState != DataRowState.Detached)
                {
                    MessageBox.Show("Невозможно удалить накладную!", "Ошибка удаления", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return returnValue;
                }
            }

            _guildBillRow.Delete();
            guilD_BILLTableAdapter1.Update(_guildBillRow);
            returnValue = 0;
            this.Close();


            return returnValue;
        }

        public int Save()
        {
            int returnValue = -1;
            //MessageBox.Show("Form_Save-" + _guildBillRow.RowState.ToString());
            if (_guildBillRow.IsNUMBERNull())
            {
                MessageBox.Show(this, "Не заполнено обязательное поле \"Номер\".\nИзменения не будут сохранены", "Обязательное поле", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else
            {
                guilD_BILLTableAdapter1.Update(_guildBillRow);

                PRODUCT_UNITTableAdapter taPU = new PRODUCT_UNITTableAdapter();

                foreach (DataSetFSO.VIEW_GUILD_BILL_ITEMRow row in dataSetFSO1.VIEW_GUILD_BILL_ITEM.Rows)
                {
                    DataSetFSO.PRODUCT_UNITRow productUnitRow;
                    if (row.RowState == DataRowState.Added)
                    {
                        productUnitRow = taPU.GetDataByID(row.ID).FindByID(row.ID);
                        productUnitRow.GUILD_BILL_NUMBER = _guildBillRow.ID;

                        taPU.Update(productUnitRow);
                    }
                    else if (row.RowState == DataRowState.Deleted)
                    {
                        //Получаем данные удаленной строки из оригинальной версии (до удаления)
                        int rowId = (int)row[dataSetFSO1.VIEW_GUILD_BILL_ITEM.IDColumn, DataRowVersion.Original];

                        productUnitRow = taPU.GetDataByID(rowId).FindByID(rowId);
                        productUnitRow.SetGUILD_BILL_NUMBERNull();

                        taPU.Update(productUnitRow);
                    }
                }

                RefreshForm();
                returnValue = 0;
            }

            return returnValue;
        }

        public int RefreshForm()
        {
            //Очищаем все таблицы
            foreach (DataTable table in dataSetFSO1.Tables)
            {
                if (!(table is DataSetFSO.GUILD_BILLDataTable))
                {
                    table.Clear();
                }
            }

            //Заполняем постоянные для конкретного счета поля формы

            CONTRACTTableAdapter taContract = new CONTRACTTableAdapter();
            NSI_ORGANIZATIONTableAdapter taOrg = new NSI_ORGANIZATIONTableAdapter();
            NSI_TYPE_OF_ACTIVITYTableAdapter taTypeOfAct = new NSI_TYPE_OF_ACTIVITYTableAdapter();
            //NSI_CURRENCYTableAdapter taCurrency = new NSI_CURRENCYTableAdapter();

            //Находим контракт, в рамках которого создан счет
            DataSetFSO.CONTRACTRow contract = taContract.GetDataByPID(_guildBillRow.PID).First();
            radLabelContract.Text = contract.NUMBER;

            if (!contract.IsNSI_ORGANIZATION_IDNull())
            {
                radLabelOrganization.Text = taOrg.GetDataById(contract.NSI_ORGANIZATION_ID).FindByID(contract.NSI_ORGANIZATION_ID).SHORT_NAME;
            }
            else
            {
                radLabelOrganization.Text = "<Не указана>";
            }

            if (!contract.IsNSI_TYPE_OF_ACTIVITY_IDNull())
            {
                radLabelTypeOfAct.Text = taTypeOfAct.GetData().FindByID(contract.NSI_TYPE_OF_ACTIVITY_ID).NAME;
            }
            else
            {
                radLabelTypeOfAct.Text = "<Не указано>";
            }

            dataSetFSO1.AGGR_PRODUCT_UNTS.Clear();
            vieW_GUILD_BILL_ITEMTableAdapter1.FillByGuildBillId(dataSetFSO1.VIEW_GUILD_BILL_ITEM, _guildBillRow.ID);

            BindControls();
            InitializeGrid();

            return 0;
        }

        public string FormName
        {
            get
            {
                string returnString = "GUILD_BILL_";

                if (_guildBillRow.ID <= 0)
                {
                    returnString = returnString + DateTime.Now;
                }
                else
                {
                    returnString = returnString + _guildBillRow.ID;
                }

                return returnString;
            }
        }

        private void FormGuildBill_Load(object sender, EventArgs e)
        {
            //Событие на измение/добавление строки (пока используется только при добавлении товара)
            dataSetFSO1.VIEW_GUILD_BILL_ITEM.RowChanged += new DataRowChangeEventHandler(VIEW_GUILD_BILL_ITEM_RowChanged);
            //Удаление товара
            // dataSetFSO1.VIEW_DIRECT_ITEM.RowDeleted += new DataRowChangeEventHandler(VIEW_DIRECT_ITEM_RowDeleted);
            //При из изменении кол-ва товара одного наименования
            dataSetFSO1.AGGR_PRODUCT_UNTS.RowChanged += new DataRowChangeEventHandler(AGGR_PRODUCT_UNTS_RowChanged);

            radGridViewProducts.MultiSelect = true;

            RefreshForm();
        }

        #region Работа с агрегированной таблицей
        //private void radGridViewProducts_UserDeletingRow(object sender, GridViewRowCancelEventArgs e)
        //{
        //    PRODUCT_UNITTableAdapter taPU = new PRODUCT_UNITTableAdapter();
        //    foreach (GridViewRowInfo ri in e.Rows)
        //    {
        //        if (ri != null && ri.DataBoundItem != null && (ri.DataBoundItem as DataRowView).Row is DataSetFSO.VIEW_GUILD_BILL_ITEMRow)
        //        {
        //            DataSetFSO.VIEW_GUILD_BILL_ITEMRow GuildItemRow = (ri.DataBoundItem as DataRowView).Row as DataSetFSO.VIEW_GUILD_BILL_ITEMRow;

        //            DataSetFSO.PRODUCT_UNITRow puRow = taPU.GetDataByID(GuildItemRow.ID).FindByID(GuildItemRow.ID);
        //            if (puRow.IsVAT_INVOICE_IDNull())
        //            {
        //                DataSetFSO.AGGR_PRODUCT_UNTSRow aggrPayRow = (from aggrRow in dataSetFSO1.AGGR_PRODUCT_UNTS where (aggrRow.NSI_PRODUCT_ID == GuildItemRow.NSI_PRODUCT_ID) select aggrRow).First();
        //                aggrPayRow.COUNT--;
        //            }
        //            else
        //            {
        //                MessageBox.Show("Удаление невозможно, так как нельзя удалить один или несколько товаров!");
        //                e.Cancel = true;
        //            }
        //        }
        //    }
        //}

        void AGGR_PRODUCT_UNTS_RowChanged(object sender, DataRowChangeEventArgs e)
        {
            if (e.Action == DataRowAction.Change)
            {
                //MessageBox.Show(e.Action.ToString());
                DataSetFSO.AGGR_PRODUCT_UNTSRow aggrProductRow = e.Row as DataSetFSO.AGGR_PRODUCT_UNTSRow;
                //Выбираем строку грида (не датасета) по заданному NSI_PRODUCT_ID
                GridViewRowInfo rowInfo = (from rInf in radGridViewProducts.MasterTemplate.Rows where ((int)rInf.Cells[dataSetFSO1.AGGR_PRODUCT_UNTS.NSI_PRODUCT_IDColumn.ColumnName].Value == aggrProductRow.NSI_PRODUCT_ID) select rInf).FirstOrDefault();
                if (rowInfo != null)
                {
                    if (aggrProductRow.COUNT < 1)
                    {
                        rowInfo.IsVisible = false;
                    }
                    else
                    {
                        rowInfo.IsVisible = true;
                    }
                }
            }
        }

        void VIEW_GUILD_BILL_ITEM_RowChanged(object sender, DataRowChangeEventArgs e)
        {
            if (e.Action == DataRowAction.Add)
            {
                //MessageBox.Show("Добавляемся!!!");
                DataSetFSO.VIEW_GUILD_BILL_ITEMRow rowGuildItem = e.Row as DataSetFSO.VIEW_GUILD_BILL_ITEMRow;

                DataSetFSO.AGGR_PRODUCT_UNTSRow aggrProductRow = (from aggrRow in dataSetFSO1.AGGR_PRODUCT_UNTS where (aggrRow.NSI_PRODUCT_ID == rowGuildItem.NSI_PRODUCT_ID) select aggrRow).FirstOrDefault();
                //Если такой записи нет а аггрегированной таблице
                if (aggrProductRow == null)
                {
                    aggrProductRow = dataSetFSO1.AGGR_PRODUCT_UNTS.NewAGGR_PRODUCT_UNTSRow();
                    //aggrProductRow. = _payInRow.ID;
                    aggrProductRow.NSI_METER_NAME = rowGuildItem.NSI_METER_NAME;
                    aggrProductRow.NSI_PRODUCT_ID = rowGuildItem.NSI_PRODUCT_ID;
                    if (rowGuildItem.NSI_PRODUCT_ID == -1)
                    {
                        //значит данный товар - работа
                        aggrProductRow.PRODUCT_UNIT_NAME = "Работы";
                    }
                    else
                    {
                        aggrProductRow.PRODUCT_UNIT_NAME = rowGuildItem.PRODUCT_UNIT_NAME;
                    }
                    dataSetFSO1.AGGR_PRODUCT_UNTS.AddAGGR_PRODUCT_UNTSRow(aggrProductRow);
                }
                aggrProductRow.COUNT++;
            }
        }

        #endregion

        private void BindControls()
        {
            radTextBoxNumber.DataBindings.Clear();
            radTextBoxNumber.DataBindings.Add("Text", _guildBillRow, dataSetFSO1.GUILD_BILL.NUMBERColumn.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged);

            radTextBoxDescription.DataBindings.Clear();
            radTextBoxDescription.DataBindings.Add("Text", _guildBillRow, dataSetFSO1.GUILD_BILL.DESCRIPTIONColumn.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged);

            radDateTimePickerDate.DataBindings.Clear();
            radDateTimePickerDate.DataBindings.Add("Value", _guildBillRow, dataSetFSO1.GUILD_BILL.DATEColumn.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged);

        }

        private void InitializeGrid()
        {
            //Колонки для агрегированной таблицы


            //Название товара
            GridViewTextBoxColumn colProdName = new GridViewTextBoxColumn("AGGR_PRODUCT_NAME", dataSetFSO1.AGGR_PRODUCT_UNTS.PRODUCT_UNIT_NAMEColumn.ColumnName);
            colProdName.HeaderText = "Имя";
            colProdName.ReadOnly = true;

            //Количество товара
            GridViewTextBoxColumn colCount = new GridViewTextBoxColumn("AGGR_COUNT", dataSetFSO1.AGGR_PRODUCT_UNTS.COUNTColumn.ColumnName);
            colCount.HeaderText = "Кол.";
            colCount.ReadOnly = true;

            //Единица измерения
            GridViewTextBoxColumn colAggrNSIMeter = new GridViewTextBoxColumn("AGGR_NSI_METER", dataSetFSO1.AGGR_PRODUCT_UNTS.NSI_METER_NAMEColumn.ColumnName);
            colAggrNSIMeter.HeaderText = "ед.";
            colAggrNSIMeter.ReadOnly = true;


            //соединительная колонка
            GridViewTextBoxColumn colNSIProdId = new GridViewTextBoxColumn(dataSetFSO1.AGGR_PRODUCT_UNTS.NSI_PRODUCT_IDColumn.ColumnName);
            colNSIProdId.IsVisible = false;
            colNSIProdId.VisibleInColumnChooser = false;

            radGridViewProducts.MasterTemplate.Columns.Clear();
            radGridViewProducts.MasterTemplate.Columns.Add(colProdName);
            radGridViewProducts.MasterTemplate.Columns.Add(colNSIProdId);
            radGridViewProducts.MasterTemplate.Columns.Add(colCount);
            radGridViewProducts.MasterTemplate.Columns.Add(colAggrNSIMeter);

            radGridViewProducts.MasterTemplate.DataSource = dataSetFSO1.AGGR_PRODUCT_UNTS;
            radGridViewProducts.MasterTemplate.EnableGrouping = false;

            radGridViewProducts.AllowDeleteRow = false;
            radGridViewProducts.AllowAddNewRow = false;

            //Таблица для единиц товара
            GridViewTemplate PUTemplate = new GridViewTemplate();

			//календарный план
			GridViewTextBoxColumn colCalendarPlan = new GridViewTextBoxColumn("PU_CALENDAR_PLAN", dataSetFSO1.VIEW_GUILD_BILL_ITEM.CALENDAR_PLAN_NUMBERColumn.ColumnName);
			colCalendarPlan.HeaderText = "Календарный план";
			colCalendarPlan.ReadOnly = true;

			//№ счета
			GridViewTextBoxColumn colInvOutNum = new GridViewTextBoxColumn("PU_INVOICE_OUT_NUMBER", dataSetFSO1.VIEW_GUILD_BILL_ITEM.INVOICE_OUT_NUMBERColumn.ColumnName);
			colInvOutNum.HeaderText = "№ счета";
			colInvOutNum.ReadOnly = true;

            GridViewTextBoxColumn colPUName = new GridViewTextBoxColumn("PU_NAME", dataSetFSO1.VIEW_GUILD_BILL_ITEM.PRODUCT_UNIT_NAMEColumn.ColumnName);
            colPUName.HeaderText = "Наименование";
            colPUName.ReadOnly = true;

            //Цена товара
            GridViewDecimalColumn colPUCost = new GridViewDecimalColumn("PU_Cost", dataSetFSO1.VIEW_GUILD_BILL_ITEM.PRODUCT_UNIT_COSTColumn.ColumnName);
            colPUCost.HeaderText = "Цена";
            colPUCost.FormatString = "{0:N2}";

            //Валюта
            GridViewTextBoxColumn colPUCurName = new GridViewTextBoxColumn("PU_CURRENCY_NAME", dataSetFSO1.VIEW_GUILD_BILL_ITEM.NSI_CURRENCY_NAMEColumn.ColumnName);
            colPUCurName.HeaderText = "Вал.";
            colPUCurName.ReadOnly = true;

           
            // % оплаты
            GridViewDecimalColumn colPUPerPay = new GridViewDecimalColumn("PU_PER_PAY", dataSetFSO1.VIEW_GUILD_BILL_ITEM.PAY_PERColumn.ColumnName);
            colPUPerPay.HeaderText = "% оплаты";
            colPUPerPay.FormatString = "{0:N2}%";

            //Конец этапа
            GridViewDateTimeColumn colPUCPEndDate = new GridViewDateTimeColumn("PU_CP_END_DATE", dataSetFSO1.VIEW_GUILD_BILL_ITEM.CP_STAGE_END_DATEColumn.ColumnName);
            colPUCPEndDate.HeaderText = "Отгрузка";
            colPUCPEndDate.FormatString = "{0:d}";

            //№ счет-фактуры
            GridViewTextBoxColumn colVatInvNum = new GridViewTextBoxColumn("PU_VAT_INV_NUM", dataSetFSO1.VIEW_GUILD_BILL_ITEM.VAT_INVOICE_NUMBERColumn.ColumnName);
            colVatInvNum.HeaderText = "№ С-Ф";
            colVatInvNum.ReadOnly = true;

            //Дата счет-фактуры
            GridViewTextBoxColumn colVatInvDate = new GridViewTextBoxColumn("PU_VAT_INVOICE_DATE", dataSetFSO1.VIEW_GUILD_BILL_ITEM.VAT_INVOICE_DATEColumn.ColumnName);
            colVatInvDate.HeaderText = "Дата С-Ф";
            colVatInvDate.ReadOnly = true;

            ////Дата платежа
            //GridViewTextBoxColumn colPayInDate = new GridViewTextBoxColumn("PU_PAYMENT_IN_ITEM_DATE", dataSetFSO1.VIEW_INV_OUT_ITEM.PAYMENT_IN_ITEM_DATEColumn.ColumnName);
            //colPayInDate.HeaderText = "Дата платежа";
            //colPayInDate.ReadOnly = true;

            ////Сумма платежа, руб
            //GridViewTextBoxColumn colPayInSum = new GridViewTextBoxColumn("PU_PAYMENT_IN_ITEM_SUM", dataSetFSO1.VIEW_INV_OUT_ITEM.PAYMENT_IN_ITEM_SUMColumn.ColumnName);
            //colPayInSum.HeaderText = "Сумма платежа, руб";
            //colPayInSum.ReadOnly = true;

            //Статус изделия
            GridViewTextBoxColumn colProductState = new GridViewTextBoxColumn("PU_NSI_PRODUCT_STATE_NAME", dataSetFSO1.VIEW_GUILD_BILL_ITEM.NSI_PRODUCT_STATE_NAMEColumn.ColumnName);
            colProductState.HeaderText = "Статус изделия";
            colProductState.ReadOnly = true;

            //Соединительное поле
            GridViewTextBoxColumn colPUNSIProdId = new GridViewTextBoxColumn(dataSetFSO1.VIEW_GUILD_BILL_ITEM.NSI_PRODUCT_IDColumn.ColumnName);
            colPUNSIProdId.IsVisible = false;
            colPUNSIProdId.VisibleInColumnChooser = false;

            PUTemplate.Columns.Clear();
			PUTemplate.Columns.Add(colCalendarPlan);
			PUTemplate.Columns.Add(colInvOutNum);
            PUTemplate.Columns.Add(colPUName);
            PUTemplate.Columns.Add(colPUCost);
            PUTemplate.Columns.Add(colPUCurName);
            PUTemplate.Columns.Add(colPUPerPay);
            PUTemplate.Columns.Add(colPUCPEndDate);
            PUTemplate.Columns.Add(colPUNSIProdId);
            PUTemplate.Columns.Add(colVatInvNum);
            PUTemplate.Columns.Add(colVatInvDate);
            PUTemplate.Columns.Add(colProductState);
            PUTemplate.DataSource = dataSetFSO1.VIEW_GUILD_BILL_ITEM;
            PUTemplate.ShowFilteringRow = false;
            PUTemplate.AutoSizeColumnsMode = GridViewAutoSizeColumnsMode.Fill;
            PUTemplate.AllowAddNewRow = false;
            PUTemplate.AllowDeleteRow = false;
            PUTemplate.ReadOnly = true;

            radGridViewProducts.Templates.Clear();
            radGridViewProducts.Templates.Add(PUTemplate);

            GridViewRelation relation = new GridViewRelation(radGridViewProducts.MasterTemplate, PUTemplate);
            relation.ParentColumnNames.Add(dataSetFSO1.AGGR_PRODUCT_UNTS.NSI_PRODUCT_IDColumn.ColumnName);
            relation.ChildColumnNames.Add(dataSetFSO1.VIEW_GUILD_BILL_ITEM.NSI_PRODUCT_IDColumn.ColumnName);

            radGridViewProducts.Relations.Clear();
            radGridViewProducts.Relations.Add(relation);
        }

        private void radButtonAdd_Click(object sender, EventArgs e)
        {
            DialogFormSelectObject selectPUDialog = new DialogFormSelectObject(ObjctTypeEnum.PRUDUCT_UNIT_FOR_FORMS, _guildBillRow.PID);
            //Заполняем только теми товарами цена на которые указана в валюте счета
            (selectPUDialog.Control as UserControlSearchPrUnitByID).FillGridForGuildBill(_guildBillRow.PID);
            if (selectPUDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                foreach (GridViewRowInfo rowInf in selectPUDialog.SelectedRows)
                {
                    DataRowView drv = (DataRowView)rowInf.DataBoundItem;
                    if (drv != null && drv.Row is DataSetFSO.VIEW_SEARCH_P_U_FOR_FORMSRow)
                    {
                        DataSetFSO.VIEW_SEARCH_P_U_FOR_FORMSRow productUnitRow = drv.Row as DataSetFSO.VIEW_SEARCH_P_U_FOR_FORMSRow;

                        try
                        {
                            DataSetFSO.VIEW_GUILD_BILL_ITEMRow rowGuildItem = dataSetFSO1.VIEW_GUILD_BILL_ITEM.NewVIEW_GUILD_BILL_ITEMRow();

                            rowGuildItem.GUILD_BILL_NUMBER_ID = _guildBillRow.ID;
                            rowGuildItem.ID = productUnitRow.ID;
                            rowGuildItem.CP_STAGE_ID = productUnitRow.CP_STAGE_ID;
                            //правки эксепшенов
                            rowGuildItem.GUILD_BILL_NUMBER = "";
                            rowGuildItem.DIRECT_NUMBER = "";
                            if (!productUnitRow.IsNSI_PRODUCT_IDNull())
                            {
                                rowGuildItem.NSI_PRODUCT_ID = productUnitRow.NSI_PRODUCT_ID;
                            }
                            //значит это работа
                            else
                            {
                                rowGuildItem.NSI_PRODUCT_ID = -1;
                                //В базе это значение null поэтому приравниваем к единице
                                //productUnitRow.NSI_PRODUCT_ID = -1;
                            }
                            rowGuildItem.PRODUCT_UNIT_NAME = productUnitRow.NAME;
                            rowGuildItem.CP_STAGE_END_DATE = productUnitRow.CP_STAGE_END_DATE;
                            rowGuildItem.CP_STAGE_NUMBER = productUnitRow.CP_STAGE_NUMBER;
                            rowGuildItem.PRODUCT_UNIT_COST = productUnitRow.COST;
                            rowGuildItem.NSI_CURRENCY_NAME = productUnitRow.NSI_CURRENCY_NAME;
                            rowGuildItem.PAY_PER = productUnitRow.PAY_PER;
                            rowGuildItem.NSI_METER_NAME = productUnitRow.NSI_METER_NAME;
                            rowGuildItem.NSI_CURRENCY_NAME = productUnitRow.NSI_CURRENCY_NAME;
                            rowGuildItem.PRODUCT_UNIT_COST = productUnitRow.COST;
                            rowGuildItem.VAT_INVOICE_DATE = productUnitRow.VAT_INVOICE_DATE1;
                            rowGuildItem.VAT_INVOICE_NUMBER = productUnitRow.VAT_INVOICE_NUMBER;
                            rowGuildItem.NSI_PRODUCT_STATE_NAME = productUnitRow.NSI_PRODUCT_STATE_NAME;
							rowGuildItem.CALENDAR_PLAN_NUMBER = productUnitRow.CALENDAR_PLAN_NUMBER;
							rowGuildItem.INVOICE_OUT_NUMBER = productUnitRow.INVOICE_OUT_NUMBER;
                            dataSetFSO1.VIEW_GUILD_BILL_ITEM.AddVIEW_GUILD_BILL_ITEMRow(rowGuildItem);

                            ////Изменяем аггрегированную таблицу


                        }
                        catch (ConstraintException)
                        {
                            MessageBox.Show("Данный товар уже добавлен к платежу!");
                        }
                    }
                }
            }
        }

        private void FormGuildBill_FormClosing(object sender, FormClosingEventArgs e)
        {

            //MessageBox.Show("Form_Closing-"+_guildBillRow.RowState.ToString());
			if (!AllowSave)
				return;
            if (_guildBillRow.RowState != DataRowState.Deleted && _guildBillRow.RowState != DataRowState.Detached && (_guildBillRow.RowState == DataRowState.Added || _guildBillRow.RowState == DataRowState.Modified || (dataSetFSO1.VIEW_GUILD_BILL_ITEM.GetChanges()) != null))
            {
                DialogResult result = MessageBox.Show(this, "Были внесены изменения. Сохранить?", "Сохранить изменения?", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);

                if (result == DialogResult.Yes)
                {
                    int SaveResult = this.Save();

                    if (SaveResult == -1)
                    {
                        e.Cancel = true;
                    }
                }
                else if (result == DialogResult.Cancel)
                {
                    e.Cancel = true;
                }
                else if (result == DialogResult.No)
                {
                    dataSetFSO1.RejectChanges();
                }
            }
        }

        private void radButtonDelete_Click(object sender, EventArgs e)
        {
            DataSetFSO.VIEW_GUILD_BILL_ITEMRow tmpPURow;
            foreach (GridViewRowInfo rowInf in radGridViewProducts.SelectedRows.ToList())
            {
                if ((tmpPURow = (rowInf.DataBoundItem as DataRowView).Row as DataSetFSO.VIEW_GUILD_BILL_ITEMRow) != null)
                {
                    if (tmpPURow.IsVAT_INVOICE_IDNull())
                    {
                        int nsiProdId = tmpPURow.NSI_PRODUCT_ID;
                        DataSetFSO.AGGR_PRODUCT_UNTSRow aggrPURow = (from aggrRow in dataSetFSO1.AGGR_PRODUCT_UNTS where (aggrRow.NSI_PRODUCT_ID == nsiProdId) select aggrRow).First();
                        aggrPURow.COUNT--;
                        rowInf.Delete();
                    }
                    else
                    {
                        MessageBox.Show("Удаление невозможно, так как нельзя удалить один или несколько товаров!");
                    }
                }
            }
        }

        private void radLabelContract_Click(object sender, EventArgs e)
        {
            if (!_guildBillRow.IsPIDNull())
            {
                CONTRACTTableAdapter ta = new CONTRACTTableAdapter();
                FormContract contractForm = new FormContract(ta.GetDataByPID(_guildBillRow.PID).First());
                if (!FormHelper.HasOpenedForm(contractForm.FormName))
                {
                    contractForm.MdiParent = FormHelper.MainForm;
                    contractForm.Show();
                    contractForm.Select();
                }
            }
        }

        private void radLabelOrganization_Click(object sender, EventArgs e)
        {
            if (!_guildBillRow.IsPIDNull())
            {
                CONTRACTTableAdapter ta = new CONTRACTTableAdapter();
                DataSetFSO.CONTRACTRow contract = ta.GetDataByPID(_guildBillRow.PID).First();

                if (!contract.IsNSI_ORGANIZATION_IDNull())
                {
                    NSI_ORGANIZATIONTableAdapter taOrg = new NSI_ORGANIZATIONTableAdapter();
                    FormNSIOrganization orgForm = new FormNSIOrganization(taOrg.GetDataById(contract.NSI_ORGANIZATION_ID).FindByID(contract.NSI_ORGANIZATION_ID));
                    if (!FormHelper.HasOpenedForm(orgForm.FormName))
                    {
                        orgForm.MdiParent = FormHelper.MainForm;
                        orgForm.Show();
                        orgForm.Select();
                    }
                }
            }
        }



    }
}
